package com.atguigu.spzx.manager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.manager.interceptor.CategoryDataListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.manager.service.CategoryService;
import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.model.vo.product.CategoryExcelVo;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public List<Category> findByParentId(Long parentId) {
        //调用根据父id查询商品分类方法
        List<Category> list=categoryMapper.selectByParentId(parentId);
        //遍历分类
        list.forEach(category -> {
            //调用方法判断是否有子分类
        Integer count=categoryMapper.selectChildren(category.getId());
        //设置是否有子分类 满足>0设置
        category.setHasChildren(count>0);
        });
        return list;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            //调用CateforyMapper中查询所有的分类的方法
           List<Category> categoryList= categoryMapper.findAll();
           //创建一个集合
            List<CategoryExcelVo> categoryExcelVoList=new ArrayList<>();
            //遍历所有类型
            categoryList.forEach(category -> {
                //创建CategoryExcelVo对象
                CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
                //将Category中的属性值赋值给CategoryExcelVo对象
                BeanUtils.copyProperties(category,categoryExcelVo);
                //将 CategoryExcelVo对象添加到集合中
                categoryExcelVoList.add(categoryExcelVo);
            });
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class).autoCloseStream(Boolean.FALSE).sheet("商品分类信息")
                    .doWrite(categoryExcelVoList);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            try {
                response.getWriter().println(JSON.toJSONString(map));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),CategoryExcelVo.class,new CategoryDataListener(categoryMapper)).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
